package org.rency.common.utils.tool;

import java.lang.management.ManagementFactory;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 随机数、随机字符串工具类
 * @author: user_rcy@163.com
 * <p>Created on 2015年11月4日</p>
 * @version: V1.0.0
 * @since JDK 1.8
 */
public class GeneratorUtils {

	/**
	 * 生成UUID(无 "-" 符号)
	 * @return
	 */
	public static String genetator(){
		UUID uuid = UUID.randomUUID();
		return uuid.toString().replace("-", "").toUpperCase();
	}

	/**
	 * 生成序列号
	 * @param length 主键长度(建议长度25位)
	 * @return
	 */
	public synchronized static String generateIdWithPID(int length){
		StringBuilder builder = new StringBuilder();
		String dateTime = new SimpleDateFormat("yyyyMMddHHmmddSSS").format(new Date());//17
		String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
		builder.append(pid);
		builder.append(dateTime);
		if(builder.length() > length){
			builder.append(builder.subSequence(0, length));
		}else{
			int offset = length - builder.length();
			int ran = generateInteger(offset);
			builder.append(ran);
		}
		
		return builder.toString();
	}
	
	/**
	 * 生成随机数
	 * @param length 随机数长度
	 * @return
	 */
	public static int generateInteger(int length){
		StringBuilder sbBuilder = new StringBuilder();
		for(int i=0;i<length;i++){
			int ran = (int)(Math.random()*10);
			if(ran == 0){
				i--;
				continue;
			}
			sbBuilder.append(ran);
		}
		return Integer.parseInt(sbBuilder.toString());
	} 
	
	/**
	 * 生成随机字符串
	 * @param length 字符串长度
	 * @return
	 */
	public static String generateString(int length){
		int uuidLength = 32;
		int count = 0;
		if(length >=uuidLength){
			count = (length % uuidLength) == 0 ? 1: (length / uuidLength) +1;
		}else{
			count = (uuidLength % length) == 0 ? 1: (uuidLength / length) +1;
		}
		StringBuilder sbBuilder = new StringBuilder();
		for(int i=0;i<count;i++){
			sbBuilder.append(UUID.randomUUID().toString().replaceAll("-", ""));
		}
		String result = sbBuilder.substring(0,length).toUpperCase();
		return result;
	} 
	
}